<?php

require_once ('system/libraries/Controller.php');
require_once ('system/application/models/Parameters.php');
require_once ('system/application/models/Lang.php');
require_once ('system/application/models/UserModel.php');

define("_DEBUG_", "true");

class BaseController extends Controller {
	protected $parameters;
	private $langs = null;

	private $headerData = "";
	private $footerData = "";

	private $loggedIn = false;
	private $user = null;
	private $siteUrl = null;

	/**
	 * Default constructor. <br />
	 * Checks if the current user is logged in. If the user is logged in, we
	 * can get the UserModel instance with the getUser() method (null if he/she
	 * is not logged in).
	 * Also it sets up the logged in user in the session.
	 *
	 */
	protected function __construct() {
		parent::__construct ();
		$siteUrl = base_url();
		$this->load->library('session');
		$langID = $this->session->userdata("langID");
		if ($langID == false) {
			// no parameters, then check database
			$this->parameters = new Parameters();
			$query = $this->db->query("select * from parameters");
			foreach ($query->result() as $row) {

				if ($row->parameter == "default_lang") {
					$this->parameters->setLangID($row->value);
				}
				if ($row->parameter == "news_per_page") {
					$this->parameters->setNewsPerPage($row->value);
				}
			}

			$query = $this->db->query("select name from langs where langID={$this->parameters->getLangID()}");
			foreach ($query->result() as $row) {
				$this->parameters->setLangName($row->name);
			}
			$this->session->set_userdata("langID", $this->parameters->getLangID());
			$this->session->set_userdata("langName", $this->parameters->getLangName());
			$this->session->set_userdata("newsPerPage", $this->parameters->getNewsPerPage());
		} else {
			// we have default parameters
			$this->parameters = new Parameters();
			$this->parameters->setLangID($this->session->userdata("langID"));
			$this->parameters->setLangName($this->session->userdata("langName"));
			$this->parameters->setNewsPerPage($this->session->userdata("newsPerPage"));
		}

		$userID = $this->session->userdata("userID");
		if ($userID == false) {
			// not logged in
		} else {
			$this->user = new UserModel();
			$this->loggedIn = true;
			$this->user->setName($this->session->userdata("name"));
			$this->user->setPassword($this->session->userdata("password"));
			$this->user->setUserID($this->session->userdata("userID"));
			$this->user->setPassword($this->session->userdata("password"));
			$this->user->setUsername($this->session->userdata("username"));
		}

	}

	/**
	 * Method that calls smarty and renders the data that is passed.<br />
	 * It opens the $viewPage page, with options from the $contentData matrix,
	 * it sets the $pageTitle and if there are options on the right side, they are
	 * set with the $options argument.
	 *
	 * @param String $viewPage the actual page that shows up (file name)
	 * @param Array[String][String] $contentData
	 * @param String $pageTitle
	 * @param String $options
	 */
	protected function viewPage($viewPage, $contentData, $pageTitle, $options = null) {
		header("Content-Type: text/html; charset=utf-8");
		$skinDir = $this->getSkinDir();
		$contentData ['siteUrl'] = base_url();
		$contentData ['adminSiteUrl'] = base_url() ."admin";
		$this->_smartyAssign($contentData);

		$this->getHeaderData($skinDir);
		$this->getFooterData();

		$data ['skinDir'] = $skinDir;
		$data ['header'] = $this->mysmarty->fetch($skinDir . "/header.tpl.php", $this->headerData);
		if ($options != null) {
			$data ['options'] = $this->mysmarty->fetch($skinDir . "/options/" . $options . "Options.tpl.php", $contentData);
		}
		$data ['content'] = $this->mysmarty->fetch($skinDir . "/" . $viewPage . ".tpl.php", $contentData);
		$data ['footer'] = $this->mysmarty->fetch($skinDir . "/footer.tpl.php", $this->footerData);
		$data ['pageTitle'] = $pageTitle;
		$this->_smartyAssign ($data);

		$this->mysmarty->view($skinDir . "/main_view.tpl.php", $data);
	}

	/**
	 * Collects header data need for the templates.<br />
	 * Just pass the skin directory.
	 *
	 * @param String $skinDir
	 */
	private function getHeaderData($skinDir) {
		if ($this->isLoggedIn()) {
			$contentData['user'] = $this->user;
			$this->_smartyAssign($contentData);
		}
		//		$this->headerData ['logoImage'] = base_url () . "system/application/views/" . $this->getSkinDir () . "/images/logo.gif";
		if ($this->user == null) {
			$this->headerData['headerMap'] = $this->mysmarty->fetch($skinDir . "/dialogs/mapNotLoggedIn.php");
		} else {
			$this->headerData['headerMap'] = $this->mysmarty->fetch($skinDir . "/dialogs/mapLoggedIn.php");
		}
		//		$this->headerData ['headerMap'] = $this->mysmarty->fetch ( $skinDir . "/dialogs/mapLoggedIn.php" );
		$this->_smartyAssign($this->headerData);
	}

	/**
	 * Passes variables to smarty.<br />
	 * $data is a hashtable with [$key][$val] pairs.
	 *
	 * @param Array[String][String] $data
	 */
	private function _smartyAssign($data) {
		foreach ($data as $key => $val) {
			//			echo "$key => $val <br />";
			$this->mysmarty->assign($key, $val);
		}
	}

	/**
	 * Collects the footer data
	 *
	 */
	private function getFooterData() {
		$this->footerData['footer'] = "footer!";
		$this->_smartyAssign($this->footerData);
	}

	/**
	 * Just returns the flag. Constructor does the real checkup.
	 *
	 * @return boolean
	 */
	public function isLoggedIn() {
		return $this->loggedIn;
	}

	/**
	 * Destroys the session and redirect the main page.
	 *
	 */
	public function logOut() {
		$this->session->sess_destroy();
		redirect("");
	}


	/**
	 * Returns list of languages. If they are not gathers it reads from the database.<br />
	 * NOTICE: Now it returns a <b>hashtable</b> instead of a list. Key is the langID from db, and
	 * value is the lang's name
	 *
	 * @return Hashtable<langID, Lang>
	 */
	public function getAllLangs() {
		if ($this->langs == null) {
			$query = $this->db->query ( "select * from langs" );
			$this->langs = array ( );

			foreach ( $query->result () as $row ) {
				$this->langs[$row->langID] = new Lang ( $row->langID, $row->name );
				//array_push ( $this->langs, new Lang ( $row->langID, $row->name ) );
			}
		}

		return $this->langs;
	}


	/**
	 * Return the application paramtaters (default language, skin, page numbers...)
	 * @return Paramter
	 */
	public function getParameters() {
		return $this->parameters;
	}

	/**
	 * Sets the array of parameters
	 * @param Array of Paramaters $parameters
	 */
	public function setParameters($parameters) {
		$this->parameters = $parameters;
	}

	/**
	 * Gets the default skin directory
	 *
	 * @return String
	 */
	function getSkinDir() {
		// TODO: u session-u treba uvek da bude defaultni skin
		return "default";
	}

	/**
	 * Gets the defailt language dir
	 *
	 * @return String
	 */
	function getLangDir() {
		// TODO: u session-u treba uvek da bude defaultni jezik
		return "srpski";
	}

	/**
	 * Sets the loggedIn flag.
	 *
	 * @param boolean $b
	 */
	protected function setLoggedIn($b) {
		$this->loggedIn = $b;
	}

	/**
	 * Return the logged in user, or null.
	 *
	 * @return User
	 */
	public function getUser() {
		return $this->user;
	}

	/**
	 * Method that actually does the login check.<br />
	 * It checks the post paramters and looks up the database
	 *
	 * @return UserModel with the logged user, or null
	 */
	public function _logIn() {
		$username = "";
		$password = "";

		if (isset($_POST['username'])) {
			$username = $_POST['username'];
		}

		if (isset($_POST['password'])) {
			$password = md5($_POST['password']);
		}

		$sql = "select * from users where username=? and password=?";
		$args = array();
		$args[] = $username; $args[] = $password;
		$query = $this->db->query($sql, $args);
		$user = $query->row();

		if ($user == null) {
			$this->setLoggedIn(false);
			return $user;
		}
		$this->load->model('UserModel');
		$loggedUser = new UserModel();
		$loggedUser->setName($user->name);
		$loggedUser->setPassword($user->password);
		$loggedUser->setUserID($user->userID);
		$loggedUser->setUsername($user->username);

		$this->session->set_userdata('userID', $loggedUser->getUserID());
		$this->session->set_userdata('username', $loggedUser->getUsername());
		$this->session->set_userdata('password', $loggedUser->getPassword());
		$this->session->set_userdata('name', $loggedUser->getName());

		$this->setLoggedIn(true);
		return $loggedUser;
	}

	public static function print_r($var) {
		if (constant("_DEBUG_")) {
			echo "<pre>";
			print_r($var);
			echo "</pre>";
		}
	}

	protected function handleException($e) {
		echo "Exception occured: ". $e->getMessage();
	}
}

?>
